//全局工具类
const utils = {
    //去重
    setReduce(arr, name) {
        var hash = {}
        return arr.reduce(function (item, next) {
            hash[next[name]] ? "" : (hash[next[name]] = true && item.push(next))
            return item
        }, [])
    },
    //数组排序
    sortBykey(ary, key) {
        return ary.sort(function (a, b) {
            let x = a[key]
            let y = b[key]
            return x < y ? -1 : x > y ? 1 : 0
        })
    },
    matchFileSuffixType(fileName) {
        // 后缀获取
        var suffix = ""
        // 获取类型结果
        var result = ""
        try {
            var flieArr = fileName.split(".")
            suffix = flieArr[flieArr.length - 1]
        } catch (err) {
            suffix = ""
        }
        // fileName无后缀返回 false
        if (!suffix) {
            result = false
            return result
        }
        // 图片格式
        var imglist = ["png", "jpg", "jpeg", "bmp", "gif"]
        // 进行图片匹配
        result = imglist.some(function (item) {
            return item == suffix
        })
        if (result) {
            result = "image"
            return result
        }
        // 匹配txt
        var txtlist = ["txt"]
        result = txtlist.some(function (item) {
            return item == suffix
        })
        if (result) {
            result = "txt"
            return result
        }
        // 匹配 excel
        var excelist = ["xls", "xlsx"]
        result = excelist.some(function (item) {
            return item == suffix
        })
        if (result) {
            result = "excel"
            return result
        }
        // 匹配 word
        var wordlist = ["doc", "docx"]
        result = wordlist.some(function (item) {
            return item == suffix
        })
        if (result) {
            result = "word"
            return result
        }
        // 匹配 pdf
        var pdflist = ["pdf"]
        result = pdflist.some(function (item) {
            return item == suffix
        })
        if (result) {
            result = "pdf"
            return result
        }
        // 匹配 ppt
        var pptlist = ["ppt"]
        result = pptlist.some(function (item) {
            return item == suffix
        })
        if (result) {
            result = "ppt"
            return result
        }
        // 匹配 视频
        var videolist = ["mp4", "m2v", "mkv"]
        result = videolist.some(function (item) {
            return item == suffix
        })
        if (result) {
            result = "video"
            return result
        }
        // 匹配 音频
        var radiolist = ["mp3", "wav", "wmv"]
        result = radiolist.some(function (item) {
            return item == suffix
        })
        if (result) {
            result = "radio"
            return result
        }
        // 其他 文件类型
        result = "other"
        return result
    },
    getDate(type) {
        const date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()

        if (type === "start") {
            year = year - 60
        } else if (type === "end") {
            year = year + 2
        }
        month = month > 9 ? month : "0" + month
        day = day > 9 ? day : "0" + day
        return `${year}-${month}-${day}`
    },
    getDatetime(type) {
        const date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let h = date.getHours() // 小时
        let m = date.getMinutes() // 分
        let s = date.getSeconds() // 秒
        if (type === "start") {
            year = year - 60
        } else if (type === "end") {
            year = year + 2
        }
        month = month > 9 ? month : "0" + month
        day = day > 9 ? day : "0" + day
        h = h > 9 ? h : "0" + h
        m = m > 9 ? m : "0" + m
        s = s > 9 ? s : "0" + s
        return `${year}-${month}-${day} ${h}:${m}:${s}`
    },
    /**
     * 修改数量(新，以所选单位为基准)
     * @param {商品Object} item
     * @param {原有数量Number} num
     * @param {库存Number} stock
     * @param {类型Number} type (加，减，输入)
     * @param {最小值Number} min
     * @param {单位比例} unitRatio
     * @param {限购数量} limit
     * @param {增量} addNum
     */
    changeAmountNew(item, num, stock, type, min = 0, unitRatio = 1, limit = 0, addNum = 1) {
        addNum = !addNum ? 1 : addNum
        switch (type) {
            case -1:
                item.Amount = Number(item.Amount) - Number(addNum)
                if (item.Amount * unitRatio < min) {
                    item.Amount = 0
                }
                break
            case 0:
                item.Amount = num * addNum
                if (item.Amount * unitRatio < min) {
                    item.Amount = parseInt(min / unitRatio) + (min % unitRatio > 0 ? 1 : 0)
                    this.Toast("最少购买" + item.Amount + "件")
                    break
                }
                if (item.Amount * unitRatio > stock || (item.Amount * unitRatio > limit && limit > 0)) {
                    if (stock >= limit && limit > 0) {
                        item.Amount = parseInt(limit / unitRatio)
                        this.Toast("已达到限购数量")
                    } else {
                        item.Amount = parseInt(stock / unitRatio)
                        this.Toast("已达到最大库存")
                    }
                    break
                }
                break
            case 1:
                item.Amount = Number(item.Amount) + Number(addNum)
                if (item.Amount * unitRatio > stock || (item.Amount * unitRatio > limit && limit > 0)) {
                    if (stock >= limit && limit > 0) {
                        item.Amount = parseInt(limit / unitRatio)
                        this.Toast("已达到限购数量")
                    } else {
                        item.Amount = parseInt(stock / unitRatio)
                        this.Toast("已达到最大库存")
                    }
                    break
                }
                if (item.Amount * unitRatio < min) {
                    item.Amount = parseInt(min / unitRatio) + (min % unitRatio > 0 ? 1 : 0)
                    this.Toast("最少购买" + min + "件")
                    break
                }
                break
        }
    },
    /**
     * 将图片数据（string）转换为数组
     * @param {图片String} imgUrl
     */
    strToArr(imgUrl) {
        const arr = imgUrl.split(",")
        return arr
    },
    /** 获取星期几**/
    getCurrentweek() {
        const myDate = new Date()
        var days = myDate.getDay()
        switch (days) {
            case 1:
                days = "星期一"
                break
            case 2:
                days = "星期二"
                break
            case 3:
                days = "星期三"
                break
            case 4:
                days = "星期四"
                break
            case 5:
                days = "星期五"
                break
            case 6:
                days = "星期六"
                break
            case 0:
                days = "星期日"
                break
        }
        return days
    },

    /**
     * 时间格式化
     * @param {格式} format     yyyymmddHHMMSS 大小写要求严格
     * @param {需要格式化的时间} date
     */
    dateFomat(format, date) {
        const opt = {
            "y+": date.getFullYear().toString(), // 年
            "m+": (date.getMonth() + 1).toString(), // 月
            "d+": date.getDate().toString(), // 日
            "H+": date.getHours().toString(), // 时
            "M+": date.getMinutes().toString(), // 分
            "S+": date.getSeconds().toString(), // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
        }

        for (var k in opt) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(
                    RegExp.$1,
                    RegExp.$1.length == 1 ? opt[k] : ("00" + opt[k]).substr(("" + opt[k]).length),
                )
            }
        }
        return format
    },
    /**
     * 时间区间选择
     */
    today() {
        const startDate = this.dateFomat("yyyy-mm-dd", new Date())
        const endDate = this.dateFomat("yyyy-mm-dd", new Date())
        return {
            startDate,
            endDate,
        }
    },
    yesterday() {
        const yesterday = new Date(new Date().setDate(new Date().getDate() - 1))
        const startDate = this.dateFomat("yyyy-mm-dd", yesterday)
        const endDate = this.dateFomat("yyyy-mm-dd", yesterday)
        return {
            startDate,
            endDate,
        }
    },
    thisWeek() {
        const weekday = new Date().getDay() || 7
        const thisweek1 = new Date(new Date().setDate(new Date().getDate() - weekday + 1))
        const startDate = this.dateFomat("yyyy-mm-dd", thisweek1)
        const endDate = this.dateFomat("yyyy-mm-dd", new Date())
        return {
            startDate,
            endDate,
        }
    },
    thisMonth() {
        const thismonth1 = new Date(new Date().setDate(1))
        const startDate = this.dateFomat("yyyy-mm-dd", thismonth1)
        const endDate = this.dateFomat("yyyy-mm-dd", new Date())
        return {
            startDate,
            endDate,
        }
    },
    thisYear() {
        const thisyear = new Date(new Date().getFullYear(), 0, 1)
        const startDate = this.dateFomat("yyyy-mm-dd", thisyear)
        const endDate = this.dateFomat("yyyy-mm-dd", new Date())
        return {
            startDate,
            endDate,
        }
    },
    chooseMonth(date) {
        const monthStart = new Date(date.setDate(1))
        const y = this.dateFomat("yyyy", date)
        const m = this.dateFomat("m", date)
        const d = new Date(y, m, 0).getDate()
        const monthEnd = new Date(y, m - 1, d)
        const startDate = this.dateFomat("yyyy-mm-dd", monthStart)
        const endDate = this.dateFomat("yyyy-mm-dd", monthEnd)
        return {
            startDate,
            endDate,
        }
    },
    // 当月（结束时间为下月1号）
    thisMonthS() {
        const thismonth1 = new Date(new Date().setDate(1))
        const startDate = this.dateFomat("yyyy-mm-dd", thismonth1)
        let y = thismonth1.getFullYear()
        let m = thismonth1.getMonth()
        if (m === 11) {
            m = -1
            y = y + 1
        }
        const _lastMonth = new Date(y, m + 1)
        const endDate = this.dateFomat("yyyy-mm-dd", _lastMonth)
        return {
            startDate,
            endDate,
        }
    },
    // 结束时间为下月1号
    chooseMonthS(date) {
        const monthStart = new Date(date.setDate(1))
        let y = date.getFullYear()
        let m = date.getMonth()
        if (m === 11) {
            m = -1
            y = y + 1
        }
        const monthEnd = new Date(y, m + 1)
        const startDate = this.dateFomat("yyyy-mm-dd", monthStart)
        const endDate = this.dateFomat("yyyy-mm-dd", monthEnd)
        return {
            startDate,
            endDate,
        }
    },

    // 获取上月年月(返回示例“2021-03”)
    lastMonth() {
        const nowDate = new Date()
        let y = nowDate.getFullYear()
        let m = nowDate.getMonth()
        if (m === 0) {
            m = 12
            y = y - 1
        }
        const _lastMonth = new Date(y, m - 1)
        const _data = this.dateFomat("yyyy-mm", _lastMonth)
        return _data
    },

    /** 规格描述字段整理（将“颜色_红色;尺码_大;”修改成“红色，大”）
     *  @param { 要修改的规格名称 } attrName
     */
    reSetAttr(attrName) {
        let newAttrName = ""
        if (attrName && attrName.indexOf(";") >= 0) {
            const _li = attrName.split(";")
            _li.forEach((item, index) => {
                if (item.indexOf("_") >= 0) {
                    newAttrName += item.split("_")[1] + "，"
                }
            })
        }
        if (newAttrName) {
            newAttrName = newAttrName.substring(0, newAttrName.length - 1)
        } else {
            newAttrName = attrName
        }
        return newAttrName
    },
    /*
	    函数，加法函数，用来得到精确的加法结果
	    说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
	    参数：arg1：第一个加数；arg2第二个加数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数）
	    调用：Calc.Add(arg1,arg2,d)
	    返回值：两数相加的结果
	    */
    add(arg1, arg2) {
        ;(arg1 = arg1.toString()), (arg2 = arg2.toString())
        var arg1Arr = arg1.split("."),
            arg2Arr = arg2.split("."),
            d1 = arg1Arr.length == 2 ? arg1Arr[1] : "",
            d2 = arg2Arr.length == 2 ? arg2Arr[1] : ""
        var maxLen = Math.max(d1.length, d2.length)
        var m = Math.pow(10, maxLen)
        var result = Number(((arg1 * m + arg2 * m) / m).toFixed(maxLen))
        var d = arguments[2]
        return typeof d === "number" ? Number(result.toFixed(d)) : result
    },
    /*
	函数：减法函数，用来得到精确的减法结果
	说明：函数返回较为精确的减法结果。
	参数：arg1：第一个加数；arg2第二个加数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数
	调用：Calc.Sub(arg1,arg2)
	返回值：两数相减的结果
	*/
    sub(arg1, arg2) {
        return add(arg1, -Number(arg2), arguments[2])
    },
    /*
	函数：乘法函数，用来得到精确的乘法结果
	说明：函数返回较为精确的乘法结果。
	参数：arg1：第一个乘数；arg2第二个乘数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数)
	调用：Calc.Mul(arg1,arg2)
	返回值：两数相乘的结果
	*/
    mul(arg1, arg2) {
        var r1 = arg1.toString(),
            r2 = arg2.toString(),
            m,
            resultVal,
            d = arguments[2]
        m = (r1.split(".")[1] ? r1.split(".")[1].length : 0) + (r2.split(".")[1] ? r2.split(".")[1].length : 0)
        resultVal = (Number(r1.replace(".", "")) * Number(r2.replace(".", ""))) / Math.pow(10, m)
        return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)))
    },
    /*
	函数：除法函数，用来得到精确的除法结果
	说明：函数返回较为精确的除法结果。
	参数：arg1：除数；arg2被除数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数)
	调用：Calc.Div(arg1,arg2)
	返回值：arg1除于arg2的结果
	*/
    div(arg1, arg2) {
        var r1 = arg1.toString(),
            r2 = arg2.toString(),
            m,
            resultVal,
            d = arguments[2]
        m = (r2.split(".")[1] ? r2.split(".")[1].length : 0) - (r1.split(".")[1] ? r1.split(".")[1].length : 0)
        resultVal = (Number(r1.replace(".", "")) / Number(r2.replace(".", ""))) * Math.pow(10, m)
        return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)))
    },
}

module.exports = {
    setReduce: utils.setReduce,
    sortBykey: utils.sortBykey,
    matchFileSuffixType: utils.matchFileSuffixType,
    getDate: utils.getDate,
    getDatetime: utils.getDatetime,
    sortBykey: utils.sortBykey,
    dateFomat: utils.dateFomat,
    getCurrentweek: utils.getCurrentweek,
    today: utils.today,
    yesterday: utils.yesterday,
    thisWeek: utils.thisWeek,
    thisMonth: utils.thisMonth,
    thisMonthS: utils.thisMonthS,
    thisYear: utils.thisYear,
    chooseMonth: utils.chooseMonth,
    chooseMonthS: utils.chooseMonthS,
    lastMonth: utils.lastMonth,
    reSetAttr: utils.reSetAttr,
    add: utils.add,
    sub: utils.sub,
    mul: utils.mul,
    div: utils.div,
    getPageList: utils.getPageList,
}
